package com.runshu.newsmartark.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextClock;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.alibaba.fastjson.JSON;
import com.arialyy.annotations.Download;
import com.arialyy.aria.core.Aria;
import com.arialyy.aria.core.task.DownloadTask;
import com.example.controllibrary.LockControl;
import com.open.hule.library.entity.AppUpdate;
import com.open.hule.library.utils.UpdateManager;
import com.runshu.newsmartark.R;
import com.runshu.newsmartark.base.BoxBaseActivity;
import com.runshu.newsmartark.base.MyApplication;
import com.runshu.newsmartark.common.ConstantUrl;
import com.runshu.newsmartark.dbutil.RefreshUtils;
import com.runshu.newsmartark.entity.ApkVersionEntity;
import com.runshu.newsmartark.entity.HDInfoBean;
import com.runshu.newsmartark.entity.HwInfo;
import com.runshu.newsmartark.entity.HwInfoUtils;
import com.runshu.newsmartark.entity.InventorySumEntity;
import com.runshu.newsmartark.entity.MqttBean;
import com.runshu.newsmartark.event.BindEventBus;
import com.runshu.newsmartark.event.Event;
import com.runshu.newsmartark.event.EventCode;
import com.runshu.newsmartark.mvp.contract.GetVersionContract;
import com.runshu.newsmartark.mvp.contract.HwHeartContract;
import com.runshu.newsmartark.mvp.contract.MainHomeContract;
import com.runshu.newsmartark.mvp.model.GetVersionModel;
import com.runshu.newsmartark.mvp.model.HwHeartModel;
import com.runshu.newsmartark.mvp.model.MainHomeModel;
import com.runshu.newsmartark.mvp.presenter.GetVersionPresenter;
import com.runshu.newsmartark.mvp.presenter.HwHeartPresenter;
import com.runshu.newsmartark.mvp.presenter.MainHomePresenter;
import com.runshu.newsmartark.network.netbean.ResponseBean;
import com.runshu.newsmartark.networkstate.annotation.NetworkSubscribe;
import com.runshu.newsmartark.networkstate.type.NetFilterType;
import com.runshu.newsmartark.networkstate.type.NetType;
import com.runshu.newsmartark.service.SyncDataService;
import com.runshu.newsmartark.util.CountDownTimer;
import com.runshu.newsmartark.util.DensityUtils;
import com.runshu.newsmartark.util.MQTTManager;
import com.runshu.newsmartark.util.MacUtils;
import com.runshu.newsmartark.util.NetStatusUtils;
import com.runshu.newsmartark.util.RefUtil;
import com.runshu.newsmartark.util.SoundPoolUtils;
import com.runshu.newsmartark.util.StringUtils;
import com.runshu.newsmartark.util.TextDrawableUtils;
import com.runshu.newsmartark.util.common.AppUtils;
import com.runshu.newsmartark.util.common.LogUtil;
import com.runshu.newsmartark.util.common.SharedPreferencesUtils;
import com.runshu.newsmartark.util.common.ToastUtils;
import com.runshu.newsmartark.util.widget.CommonShowDialog;
import com.runshu.newsmartark.util.y.nativelog.NLogUtil;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.wch.ch34xuartdriver.CH34xUARTDriver;

import static com.runshu.newsmartark.common.ConstantUrl.HEART_BEAT_IOT;
import static com.runshu.newsmartark.common.ConstantUrl.Share_XD_END_TIME;
import static com.runshu.newsmartark.common.ConstantUrl.Share_XD_START_TIME;
import static com.runshu.newsmartark.common.ConstantUrl.Share_XD_STATE_MODEL;
import static com.runshu.newsmartark.common.ConstantUrl.Share_isAdmin;
import static com.runshu.newsmartark.common.ConstantUrl.Share_isFirstMqtt;
import static com.runshu.newsmartark.util.MQTTManager.SUB_TOPIC;
import static com.runshu.newsmartark.util.MQTTManager.PUB_TOPIC;

@BindEventBus
public class MainActivity extends BoxBaseActivity implements ViewTreeObserver.OnGlobalLayoutListener, MainHomeContract.View, GetVersionContract.View, HwHeartContract.View {
    private static final String TAG = "MainActivity";
    final int RESULT_CODE=101;
    final int REQUEST_CODE=1;
    @BindView(R.id.tv_date)
    TextView mTvDate;
    @BindView(R.id.tv_hospital_name)
    TextView tvHospitalName;

    @BindView(R.id.tv_change_km)
    TextView tv_change_km;
    @BindView(R.id.tv_box_name)
    TextView tvBoxName;

    @BindView(R.id.img_weather)
    ImageView mImgWeather;
    @BindView(R.id.tv_wendu)
    TextView mTvWendu;
    @BindView(R.id.tv_info)
    TextView mTvInfo;
    @BindView(R.id.rela_info)
    RelativeLayout mRelaInfo;
    @BindView(R.id.tv_name)
    TextView mTvName;
    @BindView(R.id.rela_exit)
    RelativeLayout mRelaExit;
    @BindView(R.id.tv_stock_num)
    TextView mTvStockNum;
    @BindView(R.id.tv_hint_opean)
    TextView mTvHintOpean;
    @BindView(R.id.rela_opean_door)
    RelativeLayout mRelaOpeanDoor;
    @BindView(R.id.tv_hint_manager)
    TextView mTvHintManager;
    @BindView(R.id.rela_manager_door)
    RelativeLayout mRelaManagerDoor;
    @BindView(R.id.img_phone)
    ImageView mImgPhone;
    @BindView(R.id.tv_mac_rigth)
    TextView mTvMacRigth;
    @BindView(R.id.tv_mac_left)
    TextView mTvMacLeft;
    @BindView(R.id.tv_exit)
    TextView mTvExit;
    @BindView(R.id.tv_time)
    TextClock mTvTime;
    @BindView(R.id.tv_search_all)
    TextView mTvSearchAll;
    @BindView(R.id.rela_search_pro)
    RelativeLayout mRelaSearchPro;
    @BindView(R.id.tv_wdu)
    TextView mTvWdu;
    @BindView(R.id.tv_sdu)
    TextView mTvSdu;
    @BindView(R.id.rela_wendu)
    View relaWendu;
    @BindView(R.id.tv_hint)
    TextView mTvHint;
    @BindView(R.id.rela_shidu)
    View relaShidu;
    @BindView(R.id.icon_logo)
    ImageView icon_logo;
    private CommonShowDialog commonShowDialog;
    private final String macAddress = MacUtils.getFormatMacAddr();  //"EA06GC27A573";
    private MainHomePresenter homePresenter;
    private GetVersionPresenter versionPresenter;
    private HwHeartPresenter heartPresenter;
    private CountDownTimer timerDialog;
    private CountDownTimer timerExit;
    final static int COUNTS = 5;//点击次数
    final static long DURATION = 3 * 1000;//规定有效时间
    long[] mHits = new long[COUNTS];
    private static final String ACTION_USB_PERMISSION = "cn.wch.wchusbdriver.USB_PERMISSION";
    public static boolean isOperation;
    /**
     * 所需的所有权限信息
     */
    private static final String[] NEEDED_PERMISSIONS = new String[]{
            Manifest.permission.CAMERA,
            Manifest.permission.READ_PHONE_STATE,
            ACTION_USB_PERMISSION

    };

    private static final int ACTION_REQUEST_PERMISSIONS = 0x001;
    private LocalBroadcastManager lbm;
    //温控
    private int retval;
    public boolean isOpen = false;
    private MyHandler wenkHandler;

    public int time = 1000 * 60 * 30;
    MQTTManager mqttManager;

    private CommonShowDialog ShowPanDianDialog;
    public Handler updateHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            versionPresenter.getVersionInfo(String.valueOf(MacUtils.getLocalVersion(context)));
            updateHandler.sendEmptyMessageDelayed(1, time);
            return true;
        }
    });

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Aria.get(this).getDownloadConfig().setMaxTaskNum(1);
        Aria.download(this).register();
        //你也可以在这里初始化，对当前页面网络实时监听
        RefreshUtils.getInstance();

        UsbManager();
        if (!isOpen) {
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    UsbManager();
                }
            }, 3000); // 延时3秒
        }
        //开门状态关门关灯`
//        BoxBaseActivity.ctx.SetLightStatus(0);
//        if (isCloseDoor()) {
//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                BoxBaseActivity.ctx.SetNotActionDoorStatus(0);
//
//            }
//        }, 100);
//        }
        BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
            public void onReceive(Context context, Intent intent) {
                String action = intent.getAction();
                if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
                    Toast.makeText(getApplicationContext(), "USB已移除", Toast.LENGTH_SHORT).show();
                    isOpen = false;

                } else if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
                    Toast.makeText(getApplicationContext(), "USB已连接", Toast.LENGTH_SHORT).show();
                    UsbManager();

                    if (!isOpen) {
                        new Handler().postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                UsbManager();
                            }
                        }, 3000); // 延时3秒



                    }
                }
            }
        };

        IntentFilter usbDeviceStateFilter = new IntentFilter();
        usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        usbDeviceStateFilter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        registerReceiver(mUsbReceiver, usbDeviceStateFilter);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_mainm;
    }

    @Override
    protected void initView() {
        lbm = LocalBroadcastManager.getInstance(this);
        heartPresenter = new HwHeartPresenter(this, new HwHeartModel());
        homePresenter = new MainHomePresenter(this, new MainHomeModel());
        versionPresenter = new GetVersionPresenter(this, new GetVersionModel());
        mTvMacRigth.setText(macAddress);
        mTvDate.setText(StringUtils.getYearMonthHourMinuteTimeChinese(Calendar.getInstance().getTimeInMillis()) + " " + StringUtils.getTodayStringWeek());
        relaWendu.setVisibility(View.GONE);
        relaShidu.setVisibility(View.GONE);


    }


    @Override
    protected void initData() {
        //清空mqtt连接
        SharedPreferencesUtils.put(context, Share_isFirstMqtt, true);
//        homePresenter.getHdInfo(macAddress);
        PUB_TOPIC = "hw/" + HwInfoUtils.getCustomerId(context) + "/" + HwInfoUtils.getHospitalId(context) + "/" + MacUtils.getFormatMacAddr();
        SUB_TOPIC = "iot/" + HwInfoUtils.getCustomerId(context) + "/" + HwInfoUtils.getHospitalId(context) + "/" + MacUtils.getFormatMacAddr();
        tvHospitalName.setText(HwInfoUtils.getHospitalName(context));
        tvBoxName.setText(HwInfoUtils.getHwCode(context));
        //没联网弹框
        if (!NetStatusUtils.isConnected(context)) {
            SoundPoolUtils.play(context, R.raw.raw_net_erro, 0);
            showNetErrorDia();
        }else {
            MQTTManager mqttManager = MQTTManager.getInstance(context);
            assert mqttManager != null;
            mqttManager.connect();
            SharedPreferencesUtils.put(context, Share_isFirstMqtt, false);
        }
        exitLogin();






    }


    @Override
    protected void bindListener() {
        tv_change_km.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                isOperation = !isOperation;
                if (isOperation) {
                    tv_change_km.setBackground(context.getResources().getDrawable(R.drawable.shape_rect_red_lineartop));
                    mTvHint.setBackground(context.getResources().getDrawable(R.drawable.shape_rect_red_linearbottom));
                    tv_change_km.setText("手术模式");
                    TextDrawableUtils.setDrawableBottom(context, mTvHint, R.mipmap.icon_white_xiala);
                    mTvHint.setPadding(0, DensityUtils.dp2px(context, 20), 0, DensityUtils.dp2px(context, 30));
                    mTvHint.setText("手术时间30分钟");

                } else {
                    tv_change_km.setBackground(context.getResources().getDrawable(R.drawable.shape_rect_white_lineartop));
                    mTvHint.setBackground(context.getResources().getDrawable(R.drawable.shape_rect_white_linearbottom));
                    tv_change_km.setText("普通模式");
                    mTvHint.setText("即时关门");
                    TextDrawableUtils.clearDrawables(mTvHint);
                    mTvHint.setPadding(0, 0, 0, 0);
                }

            }
        });
        mTvTime.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                Calendar cal = Calendar.getInstance();
                int hour = cal.get(Calendar.HOUR_OF_DAY);
                int min = cal.get(Calendar.MINUTE);
                if (min == 0 || min == 30) {
                    LogUtil.e(TAG, "现在是北京时间" + hour + ":" + min);
                    homePresenter.getInventorySum(HwInfoUtils.getCustomerId(context), HwInfoUtils.getHospitalId(context), macAddress);

                }
                Date date = cal.getTime();
                SimpleDateFormat format1 = new SimpleDateFormat("HH:mm");
                String   XD_START_TIME = (String) SharedPreferencesUtils.get(context, Share_XD_START_TIME, "设置开启时间");
                String   XD_END_TIME = (String) SharedPreferencesUtils.get(context, Share_XD_END_TIME, "设置关闭时间");
                if (format1.format(date).equals(XD_START_TIME)){
                    LockControl.cfanControl((byte) 0x11);

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                Thread.sleep(50);
                                int  XD_STATE_MODEL = (int) SharedPreferencesUtils.get(context, Share_XD_STATE_MODEL, 0);
                                if (XD_STATE_MODEL==0){
                                    LockControl.otherfanControl((byte) 0x11);
                                }else {
                                    LockControl.reserverfanControl((byte) 0x11);
                                }

                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                    }).start();
                }else if (format1.format(date).equals(XD_END_TIME)){
                    LockControl.cfanControl((byte) 0x11);
                }
            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });
    }

    @Override
    protected void onPause() {
        super.onPause();
        updateHandler.removeMessages(1);

    }

    @Override
    protected void onResume() {
        super.onResume();
        startService(new Intent(MainActivity.this, SyncDataService.class));
        homePresenter.getHdInfo(macAddress);
//        startService(new Intent(MainActivity.this, SelfCheckService.class));

        //同步接口数据（医院信息， 基本信息 ====）
        new Thread(new Runnable() {
            @Override
            public void run() {
                RefreshUtils.getInstance().refreshAll();

            }
        }).start();

        //清除管理模式
        SharedPreferencesUtils.remove(context, Share_isAdmin);
//        heartPresenter.sendHwHeart(macAddress);
        homePresenter.getInventorySum(HwInfoUtils.getCustomerId(context), HwInfoUtils.getHospitalId(context), macAddress);
        updateHandler.sendEmptyMessage(1);

    }


    private void showExitDia() {
        commonShowDialog = new CommonShowDialog(context);
        commonShowDialog.setContent("已安全退出");
        commonShowDialog.setContentHint("欢迎下次使用");
        commonShowDialog.setImgShow(R.mipmap.icon_dia_exit);
        commonShowDialog.show();
        countDownShowDia();
    }

    @OnClick({R.id.icon_logo,R.id.bt_dckmsj, R.id.tv_mac_rigth, R.id.img_phone, R.id.rela_search_pro, R.id.rela_exit, R.id.rela_opean_door, R.id.rela_manager_door, R.id.tv_exit})
    public void onViewClicked(View view) {
        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.bt_dckmsj:
                if (isOperation) {
                    showChooseTimeDialog();
                }
                break;
            case R.id.img_phone:
                LogUtil.e(TAG, NetStatusUtils.isConnected(context) + "");
                exitAfterMany();
                break;
            case R.id.rela_opean_door:
                if (timerExit != null) {
                    timerExit.cancel();
                }
                if (hasAuth()) {
                    goTakeStock(this);
                } else {
                    SoundPoolUtils.play(context, R.raw.raw_face, 0);
                    intent.setClass(context, RegisterAndRecognizeActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.rela_manager_door:
                if (timerExit != null) {
                    timerExit.cancel();
                }
                if (hasAuth()) {
//                    if (MyApplication.getUserInfoGlob().isAdmin()) {
                    intent.setClass(context, ManagerActivity.class);
                    startActivity(intent);
//                    } else {
//                        showNotAdiminDia();
//                    }
                } else {
                    //设置管理模式
                    setisAdmin();
                    SoundPoolUtils.play(context, R.raw.raw_face, 0);
                    intent.setClass(context, RegisterAndRecognizeActivity.class);
                    startActivity(intent);
                }
                break;
            case R.id.tv_exit:
                mRelaExit.setVisibility(View.GONE);
                exitLogin();
                showExitDia();
                break;
            case R.id.rela_search_pro:
                intent = new Intent(context, NewProDtaActivity.class);
                startActivity(intent);
                break;
            case R.id.tv_mac_rigth:
                LogUtil.e(TAG, NetStatusUtils.isConnected(context) + "");
                exitAfterMany();
                break;

            case R.id.icon_logo:
                ipConfig();
                break;
        }
    }

    public static int dckmsj = 1;
    public static int[] dckmsjTime = {1000 * 60 * 5, 1000 * 60 * 30, 1000 * 60 * 60, 1000 * 60 * 60 * 3};
    final String[] dckmhint = {"5分钟", "30分钟", "1小时", "3小时"};

    private void showChooseTimeDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setTitle("请选择手术时间");
        //    指定下拉列表的显示数据

        //    设置一个下拉的列表选择项
        builder.setItems(dckmhint, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dckmsj = which;
                mTvHint.setText("手术时间 " + dckmhint[dckmsj]);
            }
        });
        builder.show();

    }


    @Override
    public void getIndexCount(ResponseBean responseBean) {

        HwInfo hwInfo = (HwInfo) responseBean.pullData();
//        mTvSearchAll.setText(Html.fromHtml("在柜总库存共 " + "<font color=\"#FFB000\">" + hwInfo.getAllHwInHospitalStock() + "</font>" + " 件耗材，点击查询..."));
    }

    @Override
    public void getHdInfoSuccess(ResponseBean responseBean) {
        HDInfoBean hdInfoBean = (HDInfoBean) responseBean.pullData();
        HwInfoUtils.saveData(context, hdInfoBean);
        tvHospitalName.setText(HwInfoUtils.getHospitalName(context));
        tvBoxName.setText(HwInfoUtils.getHwCode(context));

    }

    @Override
    public void getInventorySumSuccess(ResponseBean responseBean) {
        InventorySumEntity inventorySumEntity = (InventorySumEntity) responseBean.pullData();
        if (inventorySumEntity != null) {
            mTvStockNum.setText(String.valueOf(inventorySumEntity.getCurrentNum()));
            mTvSearchAll.setText(Html.fromHtml("在柜总库存共 " + "<font color=\"#FFB000\">" + inventorySumEntity.getSumNum() + "</font>" + " 件耗材，点击查询..."));
        }
    }

    @Override
    public void OnGetVersionInfoSuccess(ResponseBean responseBean) {
        ApkVersionEntity versionEntity = (ApkVersionEntity) responseBean.pullData();
        if (versionEntity == null)
            return;
        int version_code = Integer.parseInt(versionEntity.getVersionCode());
        int localVersion = MacUtils.getLocalVersion(context);
        if (localVersion < version_code) {
            showToast((versionEntity.getVersionForcible() == 1 ? "true" : "false") + version_code + "");
            NLogUtil.i(NLogUtil.INFO_App_Need_UPDATE, "localVersion:" + localVersion + "--newVersion:" + version_code);
            if (versionEntity.getVersionForcible() == 1) {
                showToast("开始静默更新");
                downloadApk(versionEntity.getVersionUrl());

            } else
                getVersion(versionEntity.getVersionUrl(), versionEntity.getVersionMessage(), Integer.parseInt(versionEntity.getVersionCode()), versionEntity.getVersionForcible() == 1);
        }
    }

    @Override
    public void OnSendHwHeartSuccess(ResponseBean responseBean) {

    }


    @Override
    public void onError(String msg) {
        ToastUtils.showText(msg);
    }

    /**
     * @author yu
     * @time 2020/6/28  10:25 AM
     * @decs：版本更新
     */
    private void getVersion(String url, String updateInfo, int code, boolean force) {
        AppUpdate appUpdate = new AppUpdate.Builder()
                //更新地址（必传）
                .newVersionUrl(url)
                // 版本号（非必填）
                .newVersionCode(String.valueOf(code))
                // 通过传入资源id来自定义更新对话框，注意取消更新的id要定义为btnUpdateLater，立即更新的id要定义为btnUpdateNow（非必填）
                .updateResourceId(R.layout.dialog_update)
                // 更新的标题，弹框的标题（非必填，默认为应用更新）
                .updateTitle(R.string.update_title)
                // 更新内容的提示语，内容的标题（非必填，默认为更新内容）
                .updateContentTitle(R.string.update_content_lb)
                // 更新内容（非必填，默认“1.用户体验优化\n2.部分问题修复”）
                .updateInfo(updateInfo)
                // 文件大小（非必填）
                // 保存文件路径（默认前缀：Android/data/包名/files/ 文件名：download）
//                .savePath("/A/B")
                //是否采取静默下载模式（非必填，只显示更新提示，后台下载完自动弹出安装界面），否则，显示下载进度，显示下载失败
                .isSilentMode(false)
                //是否强制更新（非必填，默认不采取强制更新，否则，不更新无法使用）
                .forceUpdate(force ? 1 : 0)
                .build();
        new UpdateManager().startUpdate(MainActivity.this, appUpdate);
    }

    private void showNotAdiminDia() {
        commonShowDialog = new CommonShowDialog(context);
        commonShowDialog.setContent("您没有管理权限 ，请联系管理员！");
        commonShowDialog.setImgShow(R.mipmap.icon_exit_warn);
        commonShowDialog.show();
        countDownShowDia();
    }

    private void showNetErrorDia() {
        commonShowDialog = new CommonShowDialog(context);
        commonShowDialog.setContent("您的网络有问题，请检查网络设置！");
        commonShowDialog.setImgShow(R.mipmap.icon_exit_warn);
        commonShowDialog.show();
        countDownShowDia();
    }

    /**
     * 倒计时显示Dialog
     */
    private void countDownShowDia() {
        timerDialog = new CountDownTimer(2000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
            }

            @Override
            public void onFinish() {
                commonShowDialog.dismiss();
                timerDialog.cancel();
            }
        }.start();

        if (timerExit != null) {
            timerExit.cancel();
        }
    }


    /**
     * 倒计时显示退出
     */
    @SuppressLint("SetTextI18n")
    private void countDownExit() {
        mRelaExit.setVisibility(View.VISIBLE);
        mTvName.setText("Hi，" + MyApplication.getUserInfoGlob().getUserName());
        timerExit = new CountDownTimer(10000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                mTvExit.setText("安全退出  " + millisUntilFinished / 1000 + "s");
            }

            @Override
            public void onFinish() {
                mRelaExit.setVisibility(View.GONE);
                exitLogin();
                showExitDia();

            }
        }.start();
    }


    /**
     * 连续点击多次退出
     */
    private void exitAfterMany() {
        /**
         * 实现双击方法
         * src 拷贝的源数组
         * srcPos 从源数组的那个位置开始拷贝.
         * dst 目标数组
         * dstPos 从目标数组的那个位子开始写数据
         * length 拷贝的元素的个数
         */
        System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
        //实现左移，然后最后一个位置更新距离开机的时间，如果最后一个时间和最开始时间小于DURATION，即连续5次点击
        mHits[mHits.length - 1] = SystemClock.uptimeMillis();//System.currentTimeMillis()
        if ((mHits[mHits.length - 1] - mHits[0] <= DURATION)) {
            String tips = "您已在[" + DURATION + "]ms内连续点击【" + mHits.length + "】次了！！！" + macAddress;
            Toast.makeText(MainActivity.this, tips, Toast.LENGTH_SHORT).show();
//            rebootAction();
            finish();
        }
        if ((mHits[mHits.length - 1] - mHits[2] <= DURATION)) {
            String tips = "mac地址：" + macAddress + '\n' + " 版本号：" + AppUtils.getVersionName(context) + '\t' + " 版本code：" + MacUtils.getLocalVersion(context) + '\n' + "url:" + ConstantUrl.URL;
            Toast.makeText(MainActivity.this, tips, Toast.LENGTH_SHORT).show();
        }
    }


    /**
     * 连续点击多次退出
     */
    private void ipConfig() {
        /**
         * 实现双击方法
         * src 拷贝的源数组
         * srcPos 从源数组的那个位置开始拷贝.
         * dst 目标数组
         * dstPos 从目标数组的那个位子开始写数据
         * length 拷贝的元素的个数
         */
        System.arraycopy(mHits, 1, mHits, 0, mHits.length - 1);
        //实现左移，然后最后一个位置更新距离开机的时间，如果最后一个时间和最开始时间小于DURATION，即连续5次点击
        mHits[mHits.length - 1] = SystemClock.uptimeMillis();//System.currentTimeMillis()
        if ((mHits[mHits.length - 1] - mHits[0] <= DURATION)) {
            String tips = "您已在[" + DURATION + "]ms内连续点击【" + mHits.length + "】次了！！！" + macAddress;
            Toast.makeText(MainActivity.this, tips, Toast.LENGTH_SHORT).show();
//            rebootAction();
        }
        if ((mHits[mHits.length - 1] - mHits[2] <= DURATION)) {
            Intent intent = new Intent();
            intent.setClass(context, ManagerActivity.class);
            startActivity(intent);
        }
    }
    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onDestroy() {
        exitLogin();
        LogUtil.e(TAG, "退出程序!!!!!!");
        System.exit(0);
        super.onDestroy();
    }

    public void rebootAction() {
        String cmd = "su -c reboot";
        try {
            Runtime.getRuntime().exec(cmd);
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), "Error! Fail to reboot.", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onScanSuccess(String barcode) {
        scanToOpenDoor(barcode, false);
    }


    //event 没有管理权限
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAddClientEvent(Event event) {
        if (event.getCode() == EventCode.EventNOTADMIN) {
            showNotAdiminDia();
        } else if (event.getCode() == EventCode.EventRefreshBoxInfo) {
            tvHospitalName.setText(HwInfoUtils.getHospitalName(context));
            tvBoxName.setText(HwInfoUtils.getHwCode(context));
        } else if (event.getCode() == EventCode.EventRefreshNum) {
            //刷新数据
            homePresenter.getInventorySum(HwInfoUtils.getCustomerId(context), HwInfoUtils.getHospitalId(context), macAddress);

        } else if (event.getCode() == EventCode.EventPanDian) {
            mqttBean = (MqttBean) event.getData();
            showJieSuanDia();
        } else if (event.getCode() == EventCode.NetError) {
            SoundPoolUtils.play(context, R.raw.raw_net_erro, 0);
            showNetErrorDia();
        }else if (event.getCode() == EventCode.showExitDia){
            //安全退出弹框
            if (hasAuth()) {
                mRelaExit.setVisibility(View.VISIBLE);
                countDownExit();
            } else {
                mRelaExit.setVisibility(View.GONE);
            }
        }
    }

    @NetworkSubscribe(netFilterType = NetFilterType.ALL)
    public void netWorkChangeCallBack(NetType netType) {
        switch (netType) {
            case MOBILE:
                Log.e("MainActivity", "MainActivity 已连接移动网络");
            case WIFI:
                new Thread(new Runnable() {

                    @Override
                    public void run() {
                        try {
                            RefreshUtils.getInstance().insertHardwareLog(null);
                            Thread.sleep(3000); // 休眠3秒
                            MQTTManager mqttManager = MQTTManager.getInstance(context);
                            assert mqttManager != null;
                            boolean isFirstMqtt = (boolean) SharedPreferencesUtils.get(context, Share_isFirstMqtt, true);
                            if (!isFirstMqtt) {
                                mqttManager.subscribeMsg(SUB_TOPIC, 0);
                            } else {
                                mqttManager.connect();
                                SharedPreferencesUtils.put(context, Share_isFirstMqtt, false);
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }

                    }
                }).start();
                Log.e("MainActivity", "MainActivity 已连接到wifi");
                break;
            case NONE:
                Log.e("MainActivity", "MainActivity 网络断开");
                break;
            default:
                break;
        }
    }

    @Override
    protected void afterRequestPermission(int requestCode, boolean isAllGranted) {
        if (!checkPermissions(NEEDED_PERMISSIONS)) {
            ActivityCompat.requestPermissions(this, NEEDED_PERMISSIONS, ACTION_REQUEST_PERMISSIONS);
        }
    }

    @Override
    public void onGlobalLayout() {
        mTvDate.getViewTreeObserver().removeOnGlobalLayoutListener(this);
        if (!checkPermissions(NEEDED_PERMISSIONS)) {
            ActivityCompat.requestPermissions(this, NEEDED_PERMISSIONS, ACTION_REQUEST_PERMISSIONS);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return super.onKeyDown(keyCode, event);
    }

    public void UsbManager() {
        wenkHandler = new MyHandler(MainActivity.this);
        MyApplication.driver = new CH34xUARTDriver(
                (UsbManager) getSystemService(Context.USB_SERVICE), this,
                ACTION_USB_PERMISSION);
        if (!MyApplication.driver.isConnected()) {


            if (!isOpen) {
                int retval = MyApplication.driver.ResumeUsbPermission();
                if (retval == 0) {
                    //Resume usb device list
                    retval = MyApplication.driver.ResumeUsbList();
                    if (retval == -1)// ResumeUsbList方法用于枚举CH34X设备以及打开相关设备
                    {
                        Toast.makeText(MainActivity.this, "Open failed!",
                                Toast.LENGTH_SHORT).show();
                        MyApplication.driver.CloseDevice();
                    } else if (retval == 0) {
                        if (MyApplication.driver.mDeviceConnection != null) {
                            if (!MyApplication.driver.UartInit()) {//对串口设备进行初始化操作
                                Toast.makeText(MainActivity.this, "Initialization failed!",
                                        Toast.LENGTH_SHORT).show();
                                return;
                            }
                            Toast.makeText(MainActivity.this, "Device opened",
                                    Toast.LENGTH_SHORT).show();
                            isOpen = true;
                            new ReadThread().start();//开启读线程读取串口接收的数据
                            //配置串口波特率，函数说明可参照编程手册
                            MyApplication.driver.SetConfig(9600, Byte.parseByte("8"), Byte.parseByte("1"), Byte.parseByte("0"), Byte.parseByte("0"));


                        } else {
                            Toast.makeText(MainActivity.this, "Open failed!",
                                    Toast.LENGTH_SHORT).show();
                        }
                    } else {

                        android.app.AlertDialog.Builder builder = new android.app.AlertDialog.Builder(this);
                        builder.setTitle("未授权限");
                        builder.setMessage("确认退出吗？");
                        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                System.exit(0);
                            }
                        });
                        builder.setNegativeButton("返回", new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                // TODO Auto-generated method stub

                            }
                        });
                        builder.show();

                    }
                } else {
                    isOpen = false;
                    MyApplication.driver.CloseDevice();
                }
            } else {
                isOpen = false;
                MyApplication.driver.CloseDevice();
            }
        }
    }

    MqttBean mqttBean = new MqttBean();


    private class ReadThread extends Thread {
        @Override
        public void run() {
            byte[] buffer = new byte[4096];
            while (true) {
                try {
                    MyApplication.driver.ReadData(buffer, 4096);
                    Thread.sleep(1000 * 60 * 5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                Message msg = Message.obtain();
                if (!isOpen) {
                    break;
                }
                int length = MyApplication.driver.ReadData(buffer, 4096);
                if (length > 0) {
                    String recv = new String(buffer, 0, length);
                    msg.obj = recv;
                    wenkHandler.sendMessage(msg);
                }
            }
        }
    }

    private static class MyHandler extends Handler {
        WeakReference<MainActivity> mainActivityWeakReference;

        MyHandler(MainActivity activity) {
            mainActivityWeakReference = new WeakReference<MainActivity>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            MainActivity activity = mainActivityWeakReference.get();
            if (activity != null) {
                String wenshiInfo = msg.obj.toString();
                LogUtil.e("温控==", msg.obj.toString());
                if (wenshiInfo.startsWith("T")) {
                    String[] split1 = wenshiInfo.split("\r\n");

                    if (split1.length >= 2) {
                        String[] split = split1[0].split(",");
                        if (split.length == 2) {
                            String wendu = split[0].replace("T:", "");
                            String shidu = split[1].replace("RH:", "");
                            LogUtil.e("x", "wendu==" + wendu + "===" + "shidu===" + shidu);
                            activity.relaShidu.setVisibility(View.VISIBLE);
                            activity.relaWendu.setVisibility(View.VISIBLE);
                            activity.mTvWdu.setText(String.format("%.1f", Double.parseDouble(wendu)));
                            activity.mTvSdu.setText(String.valueOf((int) (Double.parseDouble(shidu) * 100)));
                            activity.sendTemperature(String.format("%.1f", Double.parseDouble(wendu)), String.valueOf((int) (Double.parseDouble(shidu) * 100)));
                        }


                    }
                }
            }
        }
    }

    MqttBean.HeaderBean headerBean = new MqttBean.HeaderBean();
    MqttBean.BodyBean mqttBeanBodyTemperature = new MqttBean.BodyBean();

    public void sendTemperature(String wendu, String shidu) {
        MQTTManager mqttManager = MQTTManager.getInstance(context);
        assert mqttManager != null;
        headerBean.setCommand(HEART_BEAT_IOT);
        headerBean.setCustomerId(HwInfoUtils.getCustomerId(context));
        headerBean.setHospitalId(HwInfoUtils.getHospitalId(context));
        headerBean.setMac(MacUtils.getFormatMacAddr());
        headerBean.setResultCode(0);
        mqttBeanBodyTemperature.setTemperature(wendu);
        mqttBeanBodyTemperature.setHumidity(shidu);
        mqttBean.setHeader(headerBean);
        mqttBean.setBody(mqttBeanBodyTemperature);
        mqttManager.publish(PUB_TOPIC, JSON.toJSONString(mqttBean), false, 0);

    }

    public void downloadApk(String url) {
        Aria.download(this).removeAllTask(true);
        String filePath = Environment.getExternalStorageDirectory().getPath() + ConstantUrl.FILE_APK;
        File file = new File(filePath);
        if (file.exists()) {
            file.delete();
        }
        Aria.download(this)
                .load(url)     //读取下载地址
                .setFilePath(filePath, true) //设置文件保存的完整路径
                .create();   //启动下载
    }

    /*
     * 任务完成
     */
    @Download.onTaskComplete
    protected void taskComplete(DownloadTask task) {
        showToast("下载完成");
        LogUtil.e("yyd", "下载完成！");
        LogUtil.e("YYD", "是否有权限：" + isRoot());
        install(Environment.getExternalStorageDirectory().getPath() + ConstantUrl.FILE_APK);
    }

    @Download.onTaskRunning
    public void running(DownloadTask task) {
        LogUtil.e("yyd", "下载:" + task.getConvertCurrentProgress());

    }

    @Download.onTaskFail
    public void taskFail(DownloadTask task) {
    }

    public boolean install(String apkPath) {// apkPath:apk的存储路径
        boolean result = false;
        DataOutputStream dataOutputStream = null;
        BufferedReader errorStream = null;
        try {
            // 申请su权限
            Process process = Runtime.getRuntime().exec("su");
            dataOutputStream = new DataOutputStream(process.getOutputStream());
            // 执行pm install命令
            LogUtil.e("YYD", "要安装的apk路径:" + apkPath);
            String command = "pm install -t -r " + apkPath + "\n";// -t:允许apk被安装  -r :重新安装应用，且保留应用数据
            dataOutputStream.write(command.getBytes(Charset.forName("utf-8")));
            dataOutputStream.flush();
            dataOutputStream.writeBytes("exit\n");
            dataOutputStream.flush();
            process.waitFor();
            errorStream = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String msg = "";
            String line;
            // 读取命令的执行结果
            while ((line = errorStream.readLine()) != null) {
                msg += line;
            }
            LogUtil.e("YYD", "install msg is " + msg);
            // 如果执行结果中包含Failure字样就认为是安装失败，否则就认为安装成功
            if (!msg.contains("Failure")) {
                result = true;
            }

        } catch (Exception e) {
            //ToastUtil.showLongToast(KursaalApp.context,"设备未Root,请先Root后再继续使用!");
            LogUtil.e(e.getMessage(), e + "");
            result = false;
        } finally {
            try {
                if (dataOutputStream != null) {
                    dataOutputStream.close();
                }
                if (errorStream != null) {
                    errorStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
                result = false;
                LogUtil.e("YYD", "install: " + e.toString());
            }
        }
        return result;
    }

    /**
     * 判断手机是否拥有Root权限。
     *
     * @return 有root权限返回true，否则返回false。
     */
    public static boolean isRoot() {
        boolean bool = false;
        try {
            bool = new File("/system/bin/su").exists() || new File("/system/xbin/su").exists();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bool;
    }

    //结算中弹框
    private void showJieSuanDia() {
        if (ShowPanDianDialog == null) {
            ShowPanDianDialog = new CommonShowDialog(context);
        }
        ShowPanDianDialog.setContent("正在盘点中");
        ShowPanDianDialog.setContentHint("请稍候...");
        ShowPanDianDialog.setImgShow(R.mipmap.icon_jiesuan);
        ShowPanDianDialog.show();
        ShowPanDianDialog.setCancelable(false);
        ShowPanDianDialog.showLoding();
        if (!isCloseDoor()) {
            startInventory();
        } else {
            if (ShowPanDianDialog != null) {
                ShowPanDianDialog.dismiss();
            }


            assert mqttManager != null;
            mqttManager.publish(PUB_TOPIC, JSON.toJSONString(mqttBean), false, 0);
        }


    }

    ArrayList<String> str = new ArrayList<>();
    MqttBean.BodyBean mqttBeanBody = new MqttBean.BodyBean();

    @Override
    public void onScanResult(List<HashMap<String, String>> lsTagList, long a, long b) {
        super.onScanResult(lsTagList, a, b);
        if (ShowPanDianDialog != null) {
            ShowPanDianDialog.setContentHint("已盘点" + lsTagList.size() + "件");
            if (str == null) str = new ArrayList<>();
            str.clear();
            for (int i = 0; i < lsTagList.size(); i++) {
                str.add(RefUtil.decryptRfid(lsTagList.get(i).get("epc").replace(" ", "")));
            }
            ShowPanDianDialog.dismiss();

            MQTTManager mqttManager = MQTTManager.getInstance(context);
            assert mqttManager != null;
            mqttBeanBody.setCommCode(1);
            mqttBeanBody.setConsumablesNum(lsTagList.size());
            mqttBeanBody.setRfidsList(str);
            mqttBean.setBody(mqttBeanBody);
            mqttManager.publish(PUB_TOPIC, JSON.toJSONString(mqttBean), false, 0);
            ShowPanDianDialog = null;
        }
        homePresenter.getInventorySum(HwInfoUtils.getCustomerId(context), HwInfoUtils.getHospitalId(context), macAddress);

    }
}